package search;

import java.util.Arrays;

public class InsertValueSearch { //插值查找
    public static void main(String[] args) {
        int[] arr = new int[100];
        for (int i = 0; i <100; i++) {
            arr[i] = i;
        }

        System.out.println(Arrays.toString(arr));

        int index = insertValueSearch(arr, 0, arr.length -1, 1);
        System.out.println(index);
        System.out.println(arr[10]);

    }
    //插值查找法

    /**
     * @param arr     数组
     * @param left    左边索引
     * @param right   右边索引
     * @param findVal 需要查找的值
     * @return
     */
    public static int insertValueSearch(int arr[], int left, int right, int findVal) {
        if (left > right || findVal < arr[0] || findVal > arr[arr.length - 1]) {
            return -1;
        }
        //求出mid 插值查找的关键
        int mid = left + (right - left) * (findVal - arr[left]) / (arr[right] - arr[left]);
        int midVal = arr[mid];
        if (findVal > midVal) { //向左右递归
            return insertValueSearch(arr, mid + 1, right, findVal);
        } else if (findVal < midVal) {
            return insertValueSearch(arr, left, mid - 1, findVal);
        } else {
            return mid;
        }

    }

}
